package plugin

import (
	"context"
	"github.com/bitly/go-simplejson"
	v1 "k8s.io/api/core/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
	"k8s.io/klog/v2"
	"strconv"
	"strings"
	"time"
)

func createClientSet() *kubernetes.Clientset {
	config, err := rest.InClusterConfig()
	//config, err := clientcmd.BuildConfigFromFlags("", *kubeConfig)
	if err != nil {
		panic(err)
	}
	clientSet, _ := kubernetes.NewForConfig(config)
	return clientSet
}

func getRealResourcesLoad(clientSet *kubernetes.Clientset) {
	for {
		//select {
		//case <-time.NewTimer(time.Second * 30).C:
		j, _ := clientSet.RESTClient().Get().RequestURI("https://kubernetes/apis/metrics.k8s.io/v1beta1/nodes").DoRaw(context.Background())
		res, _ := simplejson.NewJson(j)
		nodeLen := len(res.Get("items").MustArray())

		realResourceRate := make(realResourceMap, nodeLen)
		for nodeNum := 0; nodeNum < nodeLen; nodeNum++ {
			realResources := make(realResource, 1)
			nodeName := res.Get("items").GetIndex(nodeNum).Get("metadata").Get("name").MustString()
			nodeCpu := res.Get("items").GetIndex(nodeNum).Get("usage").Get("cpu").MustString()
			nodeMem := res.Get("items").GetIndex(nodeNum).Get("usage").Get("memory").MustString()

			cpu, _ := strconv.ParseInt(strings.ReplaceAll(nodeCpu, "n", ""), 10, 64)
			realResources[v1.ResourceCPU] = cpu
			mem, _ := strconv.ParseInt(strings.ReplaceAll(nodeMem, "Ki", ""), 10, 64)

			realResources[v1.ResourceMemory] = mem
			realResourceRate[nodeName] = realResources
		}

		RealResourceRate = realResourceRate
		klog.Info("RealResourceRate ", RealResourceRate)
		klog.Flush()
		time.Sleep(time.Second * 15)
		//}
	}

}
